import { Persistent, BasicKeys } from '@/utils/cache/persistent';
import { CacheTypeEnum, APP_PREFERENCE_KEY } from '@/enums/cacheEnum';
import projectSetting from '@/settings/projectSetting';
import { PreferenceInfo } from './types';

const { permissionCacheType } = projectSetting;
const isLocal = permissionCacheType === CacheTypeEnum.LOCAL;

/** 获取系统偏好设置信息 */
export function getPreferenceInfo(): PreferenceInfo | null | undefined {
  const preferenceInfo = getCache<PreferenceInfo | null | undefined>(APP_PREFERENCE_KEY);
  return preferenceInfo;
}

/** 设置系统偏好设置信息 */
export function setPreferenceInfo(info: PreferenceInfo) {
  setCache(APP_PREFERENCE_KEY, info);
}

/** 移除系统偏好设置信息 */
export function removePreferenceInfo() {
  removeCache(APP_PREFERENCE_KEY);
}

/** 获取缓存 */
function getCache<T>(key: BasicKeys) {
  const fn = isLocal ? Persistent.getLocal : Persistent.getSession;
  return fn(key) as T;
}

/** 设置缓存 */
function setCache(key: BasicKeys, value: PreferenceInfo) {
  const fn = isLocal ? Persistent.setLocal : Persistent.setSession;
  return fn(key, value, true);
}

/** 移除缓存 */
function removeCache(key: BasicKeys) {
  const fn = isLocal ? Persistent.removeLocal : Persistent.removeSession;
  return fn(key);
}
